using System;
using UnityEngine;
using UnityEngine.Events;

namespace Locomotion
{
    public class JumpCharacter : MonoBehaviour
    {
        [SerializeField] private UnityEvent onJump;
        [SerializeField] private UnityEvent onLand;
        
        [SerializeField] private JumpTrace jumpTrace;
        [SerializeField] private GroundDetector groundDetector;
        [SerializeField] private JumpArrow jumpArrow;

        private Rigidbody2D _rigidbody;

        
        private void Awake()
        {
            _rigidbody = GetComponent<Rigidbody2D>();
        }

        private void OnEnable()
        {
            GroundDetector.AnyCharacterGroundedChanged += GroundDetector_AnyCharacterGroundedChanged;
        }

        private void OnDisable()
        {
            GroundDetector.AnyCharacterGroundedChanged -= GroundDetector_AnyCharacterGroundedChanged;
        }

        private void Update()
        {
            if (!groundDetector.enabled && _rigidbody.velocity.y < 0)
            {
                groundDetector.enabled = true;
            }
        }

        private void GroundDetector_AnyCharacterGroundedChanged(GroundDetector.GroundChangedEventArgs groundChangedEventArgs)
        {
            if (!groundChangedEventArgs.GroundDetector.CompareTag(tag))
            {
                return;
            }

            if (groundChangedEventArgs.GroundDetector.IsGrounded)
            {
                _rigidbody.simulated = false;
                groundDetector.enabled = false;
                onLand.Invoke();
            }
        }

        public void PrepareJump(Vector2 targetDirection)
        {
            jumpTrace.SetDirection(targetDirection);
            jumpArrow.SetDirection(targetDirection);
            jumpArrow.Show();
        }

        public void Jump()
        {
            _rigidbody.simulated = true;
            groundDetector.enabled = false;
            jumpArrow.Hide();

            _rigidbody.velocity = jumpTrace.Velocity;
            onJump?.Invoke();
        }
    }
}